<template>
  <div class="add-allocate-page-bg">
    <!-- 面包屑 -->
    <el-breadcrumb :separator-icon="ArrowRight" style="margin-bottom: 20px">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/Goods' }">货品列表</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/Allocate' }"
        >调拨记录</el-breadcrumb-item
      >
      <el-breadcrumb-item>{{
        isEdit ? "编辑调拨" : "新增调拨"
      }}</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="form-card">
      <template #header>
        <div class="card-header" >
          <span class="card-title">{{
            isEdit ? "编辑调拨记录" : "新增调拨记录"
          }}</span>
        </div>
      </template>

      <el-form
        ref="allocateFormRef"
        :model="allocateForm"
        :rules="allocateRules"
        label-width="120px"
        class="allocate-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="货品编码" prop="goodscoding">
              <el-select
                v-model="allocateForm.goodscoding"
                placeholder="请选择货品"
                filterable
                clearable
                style="width: 100%"
                @change="handleGoodsChange"
              >
                <el-option
                  v-for="item in goodsList"
                  :key="item.goodscoding"
                  :value="item.goodscoding"
                >
                  <span>{{ item.goodsname }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">
                    {{ item.goodscoding }}
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货品名称" prop="goodsName">
              <el-input
                v-model="allocateForm.goodsName"
                placeholder="货品名称"
                readonly
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="条码" prop="barcode">
              <el-input
                v-model="allocateForm.barcode"
                placeholder="条码"
                readonly
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调拨数量" prop="num">
              <el-input-number
                v-model="allocateForm.num"
                :min="1"
                :max="999999"
                placeholder="调拨数量"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="调拨原因" prop="reason">
              <el-select
                v-model="allocateForm.reason"
                placeholder="请选择调拨原因"
                style="width: 100%"
              >
                <el-option label="仓库已满" value="仓库已满" />
                <el-option label="库存不足" value="库存不足" />
                <el-option label="货品损坏" value="货品损坏" />
                <el-option label="其他原因" value="其他原因" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调拨时间" prop="wAllocatetime">
              <el-date-picker
                v-model="allocateForm.wAllocatetime"
                type="datetime"
                placeholder="选择调拨时间"
                style="width: 100%"
                value-format="YYYY-MM-DDTHH:mm:ss.SSSSSS"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="调拨备注" prop="remark">
              <el-input
                v-model="allocateForm.remark"
                type="textarea"
                placeholder="请输入调拨备注"
                rows="3"
              />
            </el-form-item>
          </el-col>
        </el-row>
                 <el-divider content-position="left">出库信息</el-divider>

         <!-- 调试信息 -->
         <!-- <div style="margin-bottom: 10px; padding: 10px; background-color: #f5f7fa; border-radius: 4px;">
          <div>仓库列表数量: {{ warehouseList.length }}</div>
           <div>所有库位数量: {{ allLocationList.length }}</div>
           <div>出库库位数量: {{ outLocationList.length }}</div> -->
         <!-- </div>  -->

         <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出库仓库" prop="warehouseNoOut">
              <el-select
                v-model="allocateForm.warehouseNoOut"
                placeholder="请选择出库仓库"
                filterable
                clearable
                style="width: 100%"
                @change="handleOutWarehouseChange"
              >
                <el-option
                  v-for="item in warehouseList"
                  :key="item.warehouseNo"
                  :label="item.warename"
                  :value="item.warehouseNo"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出库库位" prop="locationNoOut">
              <el-select
                v-model="allocateForm.locationNoOut"
                placeholder="请选择出库库位"
                filterable
                clearable
                style="width: 100%"
                :disabled="!allocateForm.warehouseNoOut"
                @change="handleOutLocationChange"
              >
                <el-option
                   v-for="item in outLocationList"
                   :key="item.locationNo"
                   :label="`${item.locationName} (${item.locationNo})`"
                   :value="item.locationNo"
                 >
                   <div style="display: flex; justify-content: space-between; align-items: center;">
                     <span>{{ item.locationName }}</span>
                     <span style="color: #909399; font-size: 12px;">{{ item.locationNo }}</span>
                   </div>
                 </el-option>
              </el-select>
              <!-- 显示已选择的出库库位详细信息 -->
              <div v-if="allocateForm.locationNoOut && selectedOutLocation" style="margin-top: 8px; padding: 8px; background-color: #f5f7fa; border-radius: 4px; font-size: 12px;">
                <div style="color: #606266;">
                  <div><strong>库位编码：</strong>{{ selectedOutLocation.locationNo }}</div>
                  <div><strong>库位名称：</strong>{{ selectedOutLocation.locationName }}</div>
                  <div v-if="selectedOutLocation.locationType"><strong>库位类型：</strong>{{ selectedOutLocation.locationType }}</div>
                  <div v-if="selectedOutLocation.status"><strong>库位状态：</strong>
                    <el-tag :type="selectedOutLocation.status === '空闲' ? 'success' : selectedOutLocation.status === '占用' ? 'warning' : 'danger'" size="small">
                      {{ selectedOutLocation.status }}
                    </el-tag>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">入库信息</el-divider>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库仓库" prop="warehouseNoIn">
              <el-select
                v-model="allocateForm.warehouseNoIn"
                placeholder="请选择入库仓库"
                filterable
                clearable
                style="width: 100%"
                @change="handleInWarehouseChange"
              >
                <el-option
                  v-for="item in warehouseList"
                  :key="item.warehouseNo"
                  :label="item.warename"
                  :value="item.warehouseNo"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库库位" prop="locationNoIn">
              <el-select
                v-model="allocateForm.locationNoIn"
                placeholder="请选择入库库位"
                filterable
                clearable
                style="width: 100%"
                :disabled="!allocateForm.warehouseNoIn"
                @change="handleInLocationChange"
              >
                  <el-option
                   v-for="item in inLocationList"
                   :key="item.locationNo"
                   :label="`${item.locationName} (${item.locationNo})`"
                   :value="item.locationNo"
                 >
                   <div style="display: flex; justify-content: space-between; align-items: center;">
                     <span>{{ item.locationName }}</span>
                     <span style="color: #909399; font-size: 12px;">{{ item.locationNo }}</span>
                   </div>
                 </el-option>
              </el-select>
              <!-- 显示已选择的入库库位详细信息 -->
              <div v-if="allocateForm.locationNoIn && selectedInLocation" style="margin-top: 8px; padding: 8px; background-color: #f5f7fa; border-radius: 4px; font-size: 12px;">
                <div style="color: #606266;">
                  <div><strong>库位编码：</strong>{{ selectedInLocation.locationNo }}</div>
                  <div><strong>库位名称：</strong>{{ selectedInLocation.locationName }}</div>
                  <div v-if="selectedInLocation.locationType"><strong>库位类型：</strong>{{ selectedInLocation.locationType }}</div>
                  <div v-if="selectedInLocation.status"><strong>库位状态：</strong>
                    <el-tag :type="selectedInLocation.status === '空闲' ? 'success' : selectedInLocation.status === '占用' ? 'warning' : 'danger'" size="small">
                      {{ selectedInLocation.status }}
                    </el-tag>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="调拨价格" prop="tuneprice">
              <el-input-number
                v-model="allocateForm.tuneprice"
                :min="0"
                :precision="2"
                placeholder="调拨价格"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="拉取数量" prop="num">
              <el-input-number
                v-model="allocateForm.num"
                :min="0"
                :max="allocateForm.num"
                placeholder="拉取数量"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="采购人员" prop="purchaseperson">
              <el-input
                v-model="allocateForm.purchaseperson"
                placeholder="采购人员"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="制单人员" prop="listperson">
              <el-input
                v-model="allocateForm.listperson"
                placeholder="制单人员"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button
            type="primary"
            @click="submitForm"
            :loading="submitLoading"
          >
            {{ isEdit ? "更新" : "提交" }}
          </el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ArrowRight } from "@element-plus/icons-vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import service from "@/utils/request";

const router = useRouter();
const route = useRoute();

// 表单引用
const allocateFormRef = ref<FormInstance>();

// 提交加载状态
const submitLoading = ref(false);

// 判断是否为编辑模式
const isEdit = computed(() => {
  return !!route.query.id;
});

// 货品列表
const goodsList = ref<any[]>([]);

// 仓库列表
const warehouseList = ref<any[]>([]);

// 出库库位列表
const outLocationList = ref<any[]>([]);

// 入库库位列表
const inLocationList = ref<any[]>([]);

// 所有库位列表
const allLocationList = ref<any[]>([]);

// 选中的入库库位信息
const selectedInLocation = ref<any>(null);

// 选中的出库库位信息
const selectedOutLocation = ref<any>(null);

// 调拨表单
const allocateForm = reactive({
  wAllocatecoding: "",
  goodscoding: "",
  goodsName: "",
  barcode: "",
  reason: "",
  num: 1,
  wAllocatetime: "",
  warehouseNoOut: "",
  warehouseNoOutName: "",
  locationNoOut: "",
  locationNoOutName: "",
  warehouseNoIn: "",
  warehouseNoInName: "",
  locationNoIn: "",
  locationNoInName: "",
  tuneprice: 0,
  pullquantity: 0,
  remark: "",
  purchaseperson: "",
  listperson: "",
});

// 表单验证规则
const allocateRules: FormRules = {
  goodscoding: [{ required: true, message: "请选择货品", trigger: "change" }],
  num: [
    { required: true, message: "请输入调拨数量", trigger: "blur" },
    { type: "number", min: 1, message: "调拨数量必须大于0", trigger: "blur" },
  ],
  reason: [{ required: true, message: "请选择调拨原因", trigger: "change" }],
  wAllocatetime: [
    { required: true, message: "请选择调拨时间", trigger: "change" },
  ],
  warehouseNoOut: [
    { required: true, message: "请选择出库仓库", trigger: "change" },
  ],
  locationNoOut: [
    { required: true, message: "请选择出库库位", trigger: "change" },
  ],
  warehouseNoIn: [
    { required: true, message: "请选择入库仓库", trigger: "change" },
  ],
  locationNoIn: [
    { required: true, message: "请选择入库库位", trigger: "change" },
  ],
};

// 获取货品列表
const getGoodsList = async () => {
  try {
    const res = await service.get("/api/app/goods/goods");
    goodsList.value = res.data || [];
  } catch (error) {
    console.error("获取货品列表失败:", error);
    ElMessage.error("获取货品列表失败");
  }
};

// 获取仓库列表
const getWarehouseList = async () => {
  try {
    const res = await service.get("/api/app/warehouse/ware");
    warehouseList.value = res.data || [];
  } catch (error) {
    console.error("获取仓库列表失败:", error);
    ElMessage.error("获取仓库列表失败");
  }
};

// 获取所有库位列表
const getAllLocationList = async () => {
  try {
    const res = await service.get("/api/app/location/location");
    allLocationList.value = res.data || [];
    console.log("所有库位列表加载成功:", allLocationList.value);
  } catch (error) {
    console.error("获取所有库位列表失败:", error);
    ElMessage.error("获取所有库位列表失败");
  }
};

// 获取库位列表
const getLocationList = async (warehouseNo: string, isOut: boolean) => {
  if (!warehouseNo) return;

  try {
    // 根据仓库编码过滤库位
    const filteredLocations = allLocationList.value.filter(
      (location: any) => location.warehouseid === warehouseNo
    );

    if (isOut) {
      outLocationList.value = filteredLocations;
    } else {
      inLocationList.value = filteredLocations;
    }
  } catch (error) {
    console.error("获取库位列表失败:", error);
    ElMessage.error("获取库位列表失败");
  }
};

// 货品选择变化
const handleGoodsChange = async (goodscoding: string) => {
  // 清空之前的出库信息
  allocateForm.warehouseNoOut = "";
  allocateForm.warehouseNoOutName = "";
  allocateForm.locationNoOut = "";
  allocateForm.locationNoOutName = "";
  outLocationList.value = [];
  
  const selectedGoods = goodsList.value.find(
    (item) => item.goodscoding === goodscoding
  );
  if (selectedGoods) {
    allocateForm.goodsName = selectedGoods.goodsname;
    allocateForm.barcode = selectedGoods.goodsbarcodes;
    
    // 根据货品编码获取仓库和库位信息
    try {
      const res = await service.get('/api/app/goods/warehouse-location', {
        params: { goodscoding }
      });
      
             if (res.data) {
         const { warehouseName, warehouseNo, warehouseLocation, warehouseLocationNo } = res.data;
         

         
         // 直接使用API返回的仓库编码，如果仓库列表中有对应的仓库
         let targetWarehouse = warehouseList.value.find(
           item => item.warehouseNo === warehouseNo
         );
         
         // 如果没找到，再通过仓库名称查找
         if (!targetWarehouse) {
           targetWarehouse = warehouseList.value.find(
             item => item.warename === warehouseName
           );
         }
         
         if (targetWarehouse) {
           // 设置出库仓库
           allocateForm.warehouseNoOut = targetWarehouse.warehouseNo;
           allocateForm.warehouseNoOutName = targetWarehouse.warename;
           
           // 获取该仓库的库位列表
           await getLocationList(targetWarehouse.warehouseNo, true);
           
                       // 如果有库位编码，直接使用；否则通过名称查找
            let targetLocation = null;
            if (warehouseLocationNo) {
              targetLocation = outLocationList.value.find(
                item => item.locationNo === warehouseLocationNo
              );
            }
            
            if (!targetLocation && warehouseLocation) {
              targetLocation = outLocationList.value.find(
                item => item.locationName === warehouseLocation
              );
            }
            
              if (targetLocation) {
               // 设置出库库位
               allocateForm.locationNoOut = targetLocation.locationNo;
               allocateForm.locationNoOutName = targetLocation.locationName;
               // 更新出库库位显示
               selectedOutLocation.value = targetLocation;
               ElMessage.success(`已自动填充出库信息：${targetWarehouse.warename} - ${targetLocation.locationName}`);
             } else {
               // 即使没找到库位，也设置仓库信息
               ElMessage.warning(`已设置仓库：${targetWarehouse.warename}，但未找到库位：${warehouseLocation}`);
             }
         } else {
           ElMessage.warning(`未找到仓库：${warehouseName} (编码: ${warehouseNo})`);
         }
       }
    } catch (error) {
      console.error('获取货品仓库库位信息失败:', error);
      ElMessage.warning('获取货品仓库库位信息失败');
    }
  }
};

// 出库仓库变化
const handleOutWarehouseChange = (warehouseNo: string) => {
  allocateForm.locationNoOut = "";
  selectedOutLocation.value = null;
  if (warehouseNo) {
    const warehouse = warehouseList.value.find(
      (item) => item.warehouseNo === warehouseNo
    );
    if (warehouse) {
      allocateForm.warehouseNoOutName = warehouse.warename;
    }
    getLocationList(warehouseNo, true);
  } else {
    outLocationList.value = [];
  }
};

// 入库仓库变化
const handleInWarehouseChange = (warehouseNo: string) => {
  allocateForm.locationNoIn = "";
  selectedInLocation.value = null;
  if (warehouseNo) {
    const warehouse = warehouseList.value.find(
      (item) => item.warehouseNo === warehouseNo
    );
    if (warehouse) {
      allocateForm.warehouseNoInName = warehouse.warename;
    }
    getLocationList(warehouseNo, false);
  } else {
    inLocationList.value = [];
  }
};

// 入库库位变化
const handleInLocationChange = (locationNo: string) => {
  if (locationNo) {
    selectedInLocation.value = inLocationList.value.find(
      (item) => item.locationNo === locationNo
    );
  } else {
    selectedInLocation.value = null;
  }
};

// 出库库位变化
const handleOutLocationChange = (locationNo: string) => {
  if (locationNo) {
    selectedOutLocation.value = outLocationList.value.find(
      (item) => item.locationNo === locationNo
    );
  } else {
    selectedOutLocation.value = null;
  }
};

// 获取调拨详情（编辑模式）
const getAllocateDetail = async (id: string) => {
  try {
    const res = await service.get(`/api/app/goods/w-allocates/${id}`);
    const data = res.data;

    Object.assign(allocateForm, data);

    // 设置相关名称
    if (data.warehouseNoOut) {
      handleOutWarehouseChange(data.warehouseNoOut);
    }
    if (data.warehouseNoIn) {
      handleInWarehouseChange(data.warehouseNoIn);
    }
    if (data.locationNoIn) {
      handleInLocationChange(data.locationNoIn);
    }
    if (data.locationNoOut) {
      handleOutLocationChange(data.locationNoOut);
    }
  } catch (error) {
    console.error("获取调拨详情失败:", error);
    ElMessage.error("获取调拨详情失败");
  }
};

// 提交表单
const submitForm = async () => {
  if (!allocateFormRef.value) return;

  try {
    await allocateFormRef.value.validate();

    submitLoading.value = true;

    // 设置调拨编码（新增时自动生成）
    if (!isEdit.value) {
      allocateForm.wAllocatecoding = `HZA${new Date().getTime()}`;
    }

    // 设置调拨时间（如果未设置）
    if (!allocateForm.wAllocatetime) {
      allocateForm.wAllocatetime = new Date().toISOString();
    }

    const url = isEdit.value
      ? `/api/app/goods/allocate/${route.query.id}`
      : "/api/app/goods/allocate";

    const method = isEdit.value ? "put" : "post";

    await service[method](url, allocateForm);

    ElMessage.success(isEdit.value ? "更新成功" : "新增成功");
    goBack();
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error("提交失败");
  } finally {
    submitLoading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  if (allocateFormRef.value) {
    allocateFormRef.value.resetFields();
  }
};

// 返回上一页
const goBack = () => {
  router.push("/Allocate");
};

// 页面加载
onMounted(async () => {
  await Promise.all([getGoodsList(), getWarehouseList(), getAllLocationList()]);

  // 如果是编辑模式，获取详情
  if (isEdit.value && route.query.id) {
    await getAllocateDetail(route.query.id as string);
  }
});
</script>

<style scoped>
.add-allocate-page-bg {
  background: linear-gradient(135deg, #e3f0ff 0%, #f8fbff 100%);
  min-height: 100vh;
  padding: 32px;
}

.form-card {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.06);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 18px;
  font-weight: bold;
  color: #409eff;
}

.allocate-form {
  max-width: 800px;
  margin: 0 auto;
}

.el-divider {
  margin: 24px 0;
}

.el-divider__text {
  background: linear-gradient(90deg, #e3f0ff 0%, #b3e0ff 100%);
  color: #409eff;
  font-weight: bold;
}

.el-form-item__label {
  color: #409eff;
  font-weight: 500;
}

.el-button {
  border-radius: 20px;
  font-weight: 500;
  transition: box-shadow 0.2s;
  margin-right: 12px;
}

.el-button:hover {
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
}

.el-button--primary {
  background: linear-gradient(90deg, #409eff 0%, #53c0ff 100%);
  border: none;
}

.el-button--default {
  background: linear-gradient(90deg, #909399 0%, #b1b3b8 100%);
  border: none;
  color: white;
}
</style>
